package com.ansion.basedb.dao.helper;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.notify.UserChangeNotifier;
import com.ansion.log.VLog;
import com.ansion.utils.GsonUtil;
import com.ansion.utils.ResourceUtils;
import com.ansion.utils.ServerTime;

import java.util.UUID;


/**
 * Andre
 */
public class UserSyncHelper {

	private static final String TAG = UserSyncHelper.class.getSimpleName();

	// update to mmkv
    // Preference prefix
    private static final String UNSYNC_USER_PREF = "Unsync_user_Pref";
    
    public static CurrentUser getUnsyncUser(long userid) {
    	SharedPreferences sp = getSharedPreferences();
    	String strLoginJson = sp.getString(String.valueOf(userid), "");
    	if (TextUtils.isEmpty(strLoginJson)) {
    		return null;
    	}
    	CurrentUser user= GsonUtil.fromJson(strLoginJson, CurrentUser.class);
    	VLog.d(TAG, "getUnsyncUser " + user);
    	return user;
    }

    public static void setUnsyncUser(CurrentUser user) {
        SharedPreferences sp = getSharedPreferences();
        SharedPreferences.Editor editor = sp.edit();
        if (null != user) {
            if (TextUtils.isEmpty(user.getSessionTag())) {
                user.setSessionTag(UUID.randomUUID().toString());
            }
            String strLoginJson = GsonUtil.toJson(user);
            editor.putString(String.valueOf(user.getUserId()), strLoginJson);
            VLog.d(TAG, "setUnsyncUser " + strLoginJson);
            editor.commit();
        }
    }

    public static void removeUnsyncUser(long userid) {
        SharedPreferences sp = getSharedPreferences();
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(String.valueOf(userid));
        editor.commit();
        VLog.d(TAG, "remove removeUnsyncUser!");
    }
    public static void clearAll(){
    	 SharedPreferences sp = getSharedPreferences();
         SharedPreferences.Editor editor = sp.edit();
         editor.clear();
         editor.commit();
         VLog.d(TAG, "clearAll !");
    }
    
    public static void clearUnsyncUserTag(boolean isAvatar){
    		CurrentUser user = getUnsyncUser(LoginedUserMgr.getUserId());
    		if(null != user){
    			if(isAvatar){
    				user.setAvatarUpdated(true);
    				if(user.isOtherDataUpdated()){
    					removeUnsyncUser(LoginedUserMgr.getUserId());
    				}else{
                        user.setOhterdataUpdatedTime(ServerTime.getServerTimeMillisecond() + 1000);
    					setUnsyncUser(user);
    				}
    			}else{
    				user.setOtherDataUpdated(true);
    				if(user.isAvatarUpdated()){
    					removeUnsyncUser(LoginedUserMgr.getUserId());
    				}else{
                        user.setAvatarUpdatedTime(ServerTime.getServerTimeMillisecond() + 1000);
    					setUnsyncUser(user);
    				}
    			}
    		}
    		
    		
    }
    
	public static void modifyCurrentUserIfNeed(CurrentUser user) {
		CurrentUser unSyncUser = getUnsyncUser(user.getUserId());
		if (unSyncUser == null) {
			return;
		}
		if (unSyncUser.getUpdated() > user.getUpdated()) {
			UserHelper.modifyOtherData(user, unSyncUser);
		}
		if (unSyncUser.getAvatarUpdated() > user.getUpdated()) {
			UserHelper.modifyAvatar(user, unSyncUser);
		}

	}
    
    /**
     * 查看 unsync的user，是否要覆盖客户端或者服务端
     * @param user CurrentUser值
     */
	public static void dealUnSyncUser(CurrentUser user) {
		long userid = user.getUserId();
		CurrentUser unSyncUser = getUnsyncUser(userid);
		if (unSyncUser==null) {
			return;
		}
		long currentuserUpdateTime = 0L;
		long unSyncOtherdataUpdated = 0L;
		long unSyncAvatarUserUpdated = 0L;
		try {
			currentuserUpdateTime = user.getUpdated();
			if (unSyncUser != null) {
				unSyncOtherdataUpdated = unSyncUser.getOhterdataUpdated();
				unSyncAvatarUserUpdated = unSyncUser.getAvatarUpdated();
			}
		} catch (Exception e) {
			VLog.e(TAG, e);
		}
		VLog.d(TAG, "unSyncUserTime--" + unSyncOtherdataUpdated
				+ " userProfileUpdateTime--" + currentuserUpdateTime);
			if (unSyncOtherdataUpdated > currentuserUpdateTime&&!unSyncUser.isOtherDataUpdated()) {
				UserHelper.modifyOtherData(user, unSyncUser);
				LoginedUserMgr.setCurrentLoginedUser(user);
				//目前otherdata 只包括 note。调用更新note，同时删除sp。如果不成功，等待下次socket连接成功
				
				int statusType=unSyncUser.getStatus_type();
				String customStatus="";
				int sysStatusNum=-1;
				if(statusType == UserModel.STATUS_TYPE_CUSTOM){
					customStatus=unSyncUser.getNote();
//					loginedUser.setNote(customStatus);
				}else if(statusType == UserModel.STATUS_TYPE_SYS){
					
					try {
						sysStatusNum=Integer.parseInt(unSyncUser.getNote());
					} catch (Exception e) {
						VLog.e(TAG, e);
					}
				}
				UserHelper.updateStatus(statusType, customStatus, sysStatusNum);
			}
			
			//jay comment,头像上传跟tcp连接无关
//			if (unSyncAvatarUserUpdated > currentuserUpdateTime&&!unSyncUser.isAvatarUpdated()) {
//				UserHelper.modifyAvatar(user, unSyncUser);
//				UploadAvatarManager.getInstance().checkUpload();
//				LoginedUserMgr.setCurrentLoginedUser(user);
//			}
			//end.
		if (unSyncOtherdataUpdated <= currentuserUpdateTime
				&& unSyncAvatarUserUpdated <= currentuserUpdateTime) {
			removeUnsyncUser(userid);
		}

	}


    public static void dealUnSyncNickName(CurrentUser user) {
        UnSyncNickNameBean bean = getUnsyncNickName(user.getUserId());
        if (bean == null || TextUtils.isEmpty(bean.nickName)) {
            return;
        }

        VLog.d(TAG, "updatetime " + bean.updateTime + "  " + user.getUpdated() + " " + (bean.updateTime - user.getUpdated()));
        if (bean.updateTime <= user.getUpdated()) {
            return;
        }
        user.setNickName(bean.nickName);
        LoginedUserMgr.setCurrentLoginedUser(user);
        UserChangeNotifier.getInstance().notifyNameChange(String.valueOf(user.getUserId()));
    }


	public static String NICK_NAME_SUBFIX="_nickname";
	public static UnSyncNickNameBean getUnsyncNickName(long userid) {
		SharedPreferences sp = getSharedPreferences();
		String strLoginJson = sp.getString(getNickNameKey(userid), "");
		if (TextUtils.isEmpty(strLoginJson)) {
			return null;
		}
		UnSyncNickNameBean bean=GsonUtil.fromJson(strLoginJson, UnSyncNickNameBean.class);
		VLog.d(TAG, "getUnsyncNickName " + bean);
		return bean;
	}

	public static void setUnsyncNickName(UnSyncNickNameBean bean) {
		SharedPreferences sp = getSharedPreferences();
		SharedPreferences.Editor editor = sp.edit();
		if (null != bean) {

			String strJson = GsonUtil.toJson(bean);
			editor.putString(getNickNameKey(bean.uid), strJson);
			VLog.d(TAG, "setUnsyncNickName " + bean);
			editor.commit();
		}
	}

	public static void removeUnsyncNickName(long userid) {
		SharedPreferences sp = getSharedPreferences();
		SharedPreferences.Editor editor = sp.edit();
		editor.remove(getNickNameKey(userid));
		editor.commit();
		VLog.d(TAG, "remove UnsyncNickName!");
	}

	private static String getNickNameKey(long uid){

		return String.valueOf(uid) + NICK_NAME_SUBFIX;

	}
	private static volatile SharedPreferences mSharedPreferences;
	private static SharedPreferences getSharedPreferences(){
		if(mSharedPreferences == null){
			synchronized (UserSyncHelper.class){
				if(mSharedPreferences == null){
					mSharedPreferences = ResourceUtils.getSharedPreferences(UNSYNC_USER_PREF);
				}
			}
		}
		return mSharedPreferences;
	}

}

